#!/usr/bin/python
# -*- coding: utf-8 -*-
# Created on 2017-02-16 上午9:46
# @auther: chenyongbing
# @file: views.py

import os, logging

log = logging.getLogger(__name__)

from django.shortcuts import render
from django.contrib import auth
from django.http import HttpResponseRedirect
from django.http import HttpResponse

from .forms import  PasswordChangeForm
import json


def index_view(request):
    return render(request , 'templates/base.html' , {"logoname":"Ops Tools",'navs':[{"name":"title1","url":"url1"},
                                                             {"name":"title2",'childs':[
                                                                 {"name":'title2-1',"url":"url2-1"},
                                                                 {"name":'title2-2',"url":"url2-2"},
                                                             ]}]})




def _check_perm(request):
    if not request.user.is_authenticated():
        raise HttpResponseRedirect('/account/login')
    if not request.user.has_perm('abview.modify_service'):
        raise render(request, 'templates/403.html')



def login_view(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')


    user = auth.authenticate(username=username, password=password)

    if user is not None and user.is_active:
        auth.login(request, user)
        return HttpResponseRedirect('/')
    return render(request, 'templates/login.html')




def logout_view(request):
    auth.logout(request)
    return render(request, 'templates/login.html')



def password_change_view(request):
    form = PasswordChangeForm(user=request.user.username)
    if request.method == "GET":
        return render(request , 'templates/password_change.html',{'form':form})
    elif request.method == "POST":
        form=PasswordChangeForm(request.POST.copy(),user=request.user.username)
        if form.is_valid():
            auth.logout(request)
            return HttpResponseRedirect('/account/login')
    return render(request, 'templates/password_change.html', {'form': form})